package com.example.demo.方法三;

import com.example.demo.exception.CommonException;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;

import java.lang.reflect.Method;

/**
 * 重写线程池，然后指定线程异常处理器
 */
@Configuration
@EnableAsync
public class SpringAsyncConfiguration implements AsyncConfigurer {

//    @Bean(name = "asyncServiceExecutor")
//    @Override
//    public Executor getAsyncExecutor() {
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        executor.setCorePoolSize(8);
//        executor.setMaxPoolSize(16);
//        executor.setQueueCapacity(64);
//        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        executor.setThreadNamePrefix("SpringAsyncThread-");
//        return executor;
//    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SpringAsyncExceptionHandler();
    }

    static class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
            if(throwable instanceof CommonException){
                System.out.println("捕获到了自定义异常： " + ((CommonException) throwable).getMsg());
            }else {
                System.out.println("捕获到了系统异常： "+ throwable.getMessage());
            }
        }
    }

}
